package com.vast.admin.controller;


import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.ImageRenderInfo;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.RenderListener;
import com.itextpdf.text.pdf.parser.TextRenderInfo;
import com.vast.admin.entity.dto.SignatureDto;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class GetPositionTest {

    public static void main(String[] args) throws Exception {
        String filePath = "D:\\uploadFile\\contract\\12.pdf";
        String KEY_WORD = "债务人.盖章";
//        java.lang.Float[] fontPosition = getFontPosition(filePath, KEY_WORD, null);
//        System.out.println(Arrays.toString(fontPosition));
        List<SignatureDto> signaturePositions = getSignaturePosition(filePath, KEY_WORD);
        for (SignatureDto signaturePosition : signaturePositions) {
            System.out.println(signaturePosition.getPageNum()+"   "+ signaturePosition.getX()+"  " +signaturePosition.getY());
        }
    }

    /**
     * 根据pdf中的关键字，获取文字的绝对位置，从而确定签章位置
     *
     * @param filePath pdf文件的绝对地址
     * @param filePath pdf中的关键字
     * @param pageNum  pdf页数,可传null，默认设置最大页数
     * @return x与y值
     * @throws IOException
     *
     */
    private static java.lang.Float[] getFontPosition(String filePath, final String signKeyWord, Integer pageNum) throws IOException {
        final java.lang.Float[] result = new java.lang.Float[2];
        PdfReader pdfReader = new PdfReader(filePath);
        PdfReaderContentParser pdfReaderContentParser = new PdfReaderContentParser(pdfReader);
        if (null == pageNum) {
            pageNum = pdfReader.getNumberOfPages();
        }
        Rectangle pageSize = pdfReader.getPageSize(1);
        float height = pageSize.getHeight();
        float width = pageSize.getWidth();
        System.out.println("页面:width = "+width+", height = "+height);
        System.out.println("换算后："+"width = "+ (width*25.4/72) +", height = "+ (height*25.4/72) );

        for (int i = 1; i <= pageNum; i++) {
            int finalI = i;
            pdfReaderContentParser.processContent(i, new RenderListener() {
                StringBuilder sb = new StringBuilder("");
                int maxLength = signKeyWord.length();

                @Override
                public void renderText(TextRenderInfo textRenderInfo) {
                    // 只适用 单字块文档 以及 关键字整个为一个块的情况
                    String text = textRenderInfo.getText(); // 整页内容
                    System.out.println("读取内容 = "+text);
                    // 设置 关键字文本为单独的块，不然会错位
                    boolean isKeywordChunk = textRenderInfo.getText().length() == maxLength;
                    if (isKeywordChunk) {
                        // 文档按照 块 读取
                        if(text != null && !text.trim().isEmpty()) {
                            sb.delete(0, sb.length());
                            sb.append(textRenderInfo.getText());
                        }
                    } else {
                        if(text != null && !text.trim().isEmpty()){
                            // 有些文档 单字一个块的情况
                            // 拼接字符串
                            sb.append(textRenderInfo.getText());
                            // 去除首部字符串，使长度等于关键字长度
                            if (sb.length() > maxLength) {
                                sb.delete(0, sb.length() - maxLength);
                            }
                        }

                    }
                    // 判断是否匹配上
                    if (signKeyWord.equals(sb.toString())) {
//                        RectangleCentre rectangleCentre = rectangleCentreBase.copy();

                        // 计算中心点坐标

                        com.itextpdf.awt.geom.Rectangle2D.Float baseFloat = textRenderInfo.getBaseline()
                                .getBoundingRectange();
                        com.itextpdf.awt.geom.Rectangle2D.Float ascentFloat = textRenderInfo.getAscentLine()
                                .getBoundingRectange();

                        float centreX;
                        float centreY;
                        if (isKeywordChunk) {
                            centreX = baseFloat.x + ascentFloat.width / 2;
                            centreY = baseFloat.y + ((ascentFloat.y - baseFloat.y) / 2);
                        } else {
                            centreX = baseFloat.x + ascentFloat.width - (maxLength * ascentFloat.width / 2);
                            centreY = baseFloat.y + ((ascentFloat.y - baseFloat.y) / 2);
                        }

                        result[0] = centreX/width;
                        result[1] = (height - centreY)/height;
                        System.out.println(String.format("第"+finalI+"页 "+signKeyWord+" 文字域绝对位置为x:%s,y:%s", centreX,centreY));
//                        rectangleCentre.setCentreX(centreX);
//                        rectangleCentre.setCentreY(centreY);
//                        rectangleCentreList.add(rectangleCentre);
                        // 匹配完后 清除
                        sb.delete(0, sb.length());
                    }
                }


                @Override
                public void renderImage(ImageRenderInfo arg0) {
                    // nothing
                }

                @Override
                public void endTextBlock() {
                    // nothing
                }

                @Override
                public void beginTextBlock() {
                    // nothing
                }
            });
        }

        return result;
    }

    private static List<SignatureDto> getSignaturePosition(String filePath, String keyword) {
        List<SignatureDto> signatureDtos = new ArrayList<>();
        try {
            PdfReader pdfReader = new PdfReader(filePath);

            PdfReaderContentParser pdfReaderContentParser = new PdfReaderContentParser(pdfReader);
            int pageTotalNum = pdfReader.getNumberOfPages();
//            signature.setTotalPageNum(pageTotalNum);

            Rectangle pageSize = pdfReader.getPageSize(1);
            //页面高宽
            float height = pageSize.getHeight();
            float width = pageSize.getWidth();
            //页面高宽
//        System.out.println("width = "+width+", height = "+height);
//        System.out.println("换算后："+"width = "+ (width*25.4/72) +", height = "+ (height*25.4/72) );

            for (int i = 1; i <= pageTotalNum; i++) {
                int page = i;
                pdfReaderContentParser.processContent(i, new RenderListener() {
                    StringBuilder sb = new StringBuilder("");
                    String signKeyWord = keyword;
                    int maxLength = keyword.length();
                    @Override
                    public void renderText(TextRenderInfo textRenderInfo) {
//                        String text = textRenderInfo.getText(); // 整页内容
//                        if (text != null && text.contains(signature.getKeyWord())) {
//                            // 文字在page中的横坐标、纵坐标
//                            Rectangle2D.Float textFloat = textRenderInfo.getBaseline().getBoundingRectange();
//                            float x = textFloat.x;
//                            float y = textFloat.y;
//                            signature.setX(x / width);
//                            signature.setY((height - y) / height);
//                            signature.setPageNum(page);
////                            System.out.println(String.format("第" + page + "盖章文字域绝对位置为x:%s,y:%s", x, y));
//                        }

                        // 只适用 单字块文档 以及 关键字整个为一个块的情况
                        String text = textRenderInfo.getText(); // 整页内容
                        System.out.println("读取内容 = "+text);
                        // 设置 关键字文本为单独的块，不然会错位
                        boolean isKeywordChunk = textRenderInfo.getText().length() == maxLength;
                        if (isKeywordChunk) {
                            if(text != null && !text.trim().isEmpty()) {
                                // 文档按照 块 读取
                                sb.delete(0, sb.length());
                                sb.append(textRenderInfo.getText());

                            }
                        } else {
                            // 有些文档 单字一个块的情况
                            // 拼接字符串
                            if(text != null && !text.trim().isEmpty()) {
                                sb.append(textRenderInfo.getText());
                                // 去除首部字符串，使长度等于关键字长度
                                if (sb.length() > maxLength) {
                                    sb.delete(0, sb.length() - maxLength);
                                }
                            }
                        }
                        // 判断是否匹配上
                        if (signKeyWord.equals(sb.toString())) {
                            SignatureDto signatureDto = new SignatureDto(signKeyWord);
                            // 计算中心点坐标
                            com.itextpdf.awt.geom.Rectangle2D.Float baseFloat = textRenderInfo.getBaseline() .getBoundingRectange();
                            com.itextpdf.awt.geom.Rectangle2D.Float ascentFloat = textRenderInfo.getAscentLine() .getBoundingRectange();

                            float centreX;
                            float centreY;
                            if (isKeywordChunk) {
                                centreX = baseFloat.x + ascentFloat.width / 2;
                                centreY = baseFloat.y + ((ascentFloat.y - baseFloat.y) / 2);
                            } else {
                                centreX = baseFloat.x + ascentFloat.width - (maxLength * ascentFloat.width / 2);
                                centreY = baseFloat.y + ((ascentFloat.y - baseFloat.y) / 2);
                            }

                            signatureDto.setX(centreX / width);
                            signatureDto.setY((height - centreY) / height);
                            signatureDto.setPageNum(page);
                            signatureDtos.add(signatureDto);
//                            result[0] = centreX/width;
//                            result[1] = (height - centreY)/height;
//                            System.out.println(String.format("第"+finalI+"页 "+signKeyWord+" 文字域绝对位置为x:%s,y:%s", centreX,centreY));

                            // 匹配完后 清除
                            sb.delete(0, sb.length());
                        }


                    }

                    @Override
                    public void renderImage(ImageRenderInfo arg0) {
                        // TODO Auto-generated method stub
                    }

                    @Override
                    public void endTextBlock() {
                        // TODO Auto-generated method stub
                    }

                    @Override
                    public void beginTextBlock() {
                        // TODO Auto-generated method stub

                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return signatureDtos;
    }


}
